<template>
    <div class="main_box" style="padding:10px">
      <div class="add_wrap">
        <div class="tit">
          <h2>{{ dataForm.fileId ? '编辑商户资料' : '新增商户资料' }}</h2>
          <el-button type="success" plain size="small" icon="fa fa-mail-forward" @click="returnList">返回</el-button>
        </div>
        <el-form :model="dataForm" ref="dataForm" label-width="200px" :rules="roleRules">
          <el-row>
            <el-form-item prop="businessId" label="商户">
              <el-select placeholder="请选择商户" v-model="dataForm.businessId" clearable filterable>
                <el-option v-for="item in businessList" :key="item.id" :value="item.id" :label="item.name">

                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="fileUrl" label="文件" v-if="dataForm.businessId">
                <upload-img class="upload-img" @uploadFileList="getUrl" :folder="folder" :accept="fileTypeList">
                  <el-input  style="width: 100%;" placeholder="点击上传文件" v-model="dataForm.fileName"></el-input>
                </upload-img>
                  <div v-if="dataForm.fileName">
                    <img @click="preview" style="width:50px;height:auto" :src="icon"/>
                    <div>
                      {{ dataForm.fileName }}
                    </div>
                  </div>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item>
              <el-button plain type="primary" @click=" sureClick ">保 存</el-button>
              <el-button plain @click=" returnList ">取 消</el-button>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
    </div>
  </template>

  <script>
  import * as message from "@/constants/message";
  import BusinessFileApi from '@/api/business/businessFile';
  import BusinessApi from "@/api/business/business";
  import { getStorage } from '@/utils/auth';
  import UploadImg from "@/components/UploadImg"
  export default {
    data() {
      return {
        dataForm: {
          fileId: "",
          businessId:"",
          fileUrl:"",
          fileType: "",
          fileName:"",
        },
        businessList: [],
        fileType:{
          'word':['.doc','.docm','.docx'],
          "excel":[".xls",".xlsx"],
          "image":[".webp",'.jpeg',".jpg",".gif",'.png'],
          "video":[".mp4",".m2v",".mkv"],
          "ppt":[".ppt",".pptx"],
          "pdf":[".pdf"],
        },
        roleRules: {
          businessId: [
            { required: true, message: "请选择商户", trigger: "change" }
          ],
          fileUrl:[
          { required: true, message: "请选择文件", trigger: "change" }
          ],
        },
        icon:import("@/assets/img/word.png"),
      }
    },
    computed:{
      folder(){
        const {businessId} = this.dataForm
        if(businessId){
          return "bfile/"+businessId
        }else{
          return "bfile"
        }
      },
      fileTypeList(){
        const {fileType} = this
        let arr = []
        console.log()
        for(let item of Object.keys(fileType)){
          arr = arr.concat(fileType[item])
        }
        return arr.toString()
      }
    },
    components:{
      UploadImg
    },
    mounted() {
      this.init()
    },
    methods: {
      init() {
        this.getBusinessList()
        if (this.$route.query.id) {
          this.dataForm.fileId = this.$route.query.id
          this.getData()
        }
      },
      keydown(e) {
        if (e.keyCode == 32) {
          e.returnValue = false;
        }
      },

      getData() {
        BusinessFileApi.getBusinessFileInfo({
          id: this.dataForm.fileId
        }).then(res => {
          this.$Utils.bindingBean(this.dataForm, res.data)
        })
      },
      // 获取商户列表
      getBusinessList() {
        BusinessApi.listIdNameVo().then(res => {
          this.businessList = res.data
        })
      },
      getUrl(url){
        const {fileType,dataForm} = this
        Object.keys(fileType).find(item=>{
          const type = fileType[item].find(item2=>url[0].endsWith(item2))
          if(type){
            dataForm.fileType = item
            return true
          }
        })
        const index = url[0].lastIndexOf("/")
        this.icon=import(`@/assets/img/${dataForm.fileType}.png`)
        dataForm.fileName = url[0].slice(index+1)
        dataForm.fileUrl = url[0]
      },
      preview(){
        window.open(this.dataForm.fileUrl,"_bank")
      },
      sureClick() {
        this.$refs.dataForm.validate(valid => {
          if (valid) {
            // 对经营区域表进行处理，先去掉空的行，再判断是否至少加了一行数据(必须加)，最后过滤筛选出需要提交的数据
            this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {})
              .then(() => {
                if (this.dataForm.fileId) {
                  this.editData();
                } else {
                  this.addData();
                }
              });
          }
        })
      },
      addData() {
        let param = {
          fileType:this.dataForm.fileType,
          fileUrl:this.dataForm.fileUrl,
          fileName:this.dataForm.fileName,
          businessId:this.dataForm.businessId
        };
        BusinessFileApi.addBusinessFile(param).then(res => {
          this.$Utils.notifySuccess()
          this.returnList();
        })
      },
      editData() {
        let param = {
          fileId: this.dataForm.fileId,
          fileType:this.dataForm.fileType,
          fileUrl:this.dataForm.fileUrl,
          fileName:this.dataForm.fileName,
          businessId:this.dataForm.businessId
        };
        BusinessFileApi.editBusinessFile(param)
          .then(data => {
            this.$Utils.notifySuccess()
            this.returnList();
          })
      },
      returnList() {
        this.$store.dispatch('delView', this.$route);
        this.$router.push({ path: '/business/businessFileManagement' });
      }
    },

  }
  </script>
  <style lang="scss" scoped>
@import "@/assets/css/views/add.scss";
</style>
  <style lang="scss" scoped>
    .upload-img{
      ::v-deep .el-upload{
        width: 100%;
        border:none;
          .el-upload-dragger{
          width: 100%;
          height: 100%;
          border: none;
        // display: none;
        }
      }

    }
  </style>
